package com.tmeone.erpone.controller;


import com.tmeone.erpone.entity.SMenu;
import com.tmeone.erpone.service.ISMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author tmeone
 * @since 2021-04-16
 */
@RestController
public class SMenuController {


    @Autowired
    private ISMenuService functionsService;


    @ResponseBody
    @RequestMapping("/menus")
    public List<SMenu> selectFunsAll() {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal instanceof User && principal != null) {
            User user = (User) principal;
            //按用户名查询菜单权限
            List<SMenu> functions = functionsService.selectFunsAll(user.getUsername());
            return functions;
        }
        return null;
    }

    @ResponseBody
    @RequestMapping("function")
    public List<SMenu> selectListAll() {
        List<SMenu> list = functionsService.list();
        List<SMenu> list1 = new ArrayList<>();
        for (SMenu functions : list) {
            if (functions.getMenuPid().equals("0")) {
                List<SMenu> functions1 = functionsService.selectListAll(functions.getId());
                functions.setSubFunctions(functions1);
                list1.add(functions);
            }
        }
        return list1;
    }

    @ResponseBody
    @RequestMapping("/functionzi/{roleId}")
    public List<String> selectAll(@PathVariable String roleId) {
        return functionsService.getFunctionsIdsByRoleId(roleId);
    }

    @ResponseBody
    @RequestMapping("/menusName")
    public String menusName() {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal instanceof User && principal != null) {
            User user = (User) principal;
            return user.getUsername();
        }
        return null;
    }

}
